﻿using System.Collections.Generic;
using System.Linq;
using TheGameClient.Processes;

namespace TheGameClient
{
	public class MasterUiFactory
	{
		private static MasterUiFactory _instance;
		private readonly Dictionary<ulong, UiFactoryBase> _registeredFactories;

		private MasterUiFactory()
		{
			_registeredFactories = new Dictionary<ulong, UiFactoryBase>();
		}

		public static MasterUiFactory Instance
		{
			get
			{
				if (_instance == null)
					_instance = new MasterUiFactory();
				return _instance;
			}
		}

		public void RegisterProgramFactory(ulong interfaceId, UiFactoryBase instance)
		{
			if (instance != null && interfaceId != 0 && !_registeredFactories.ContainsKey(interfaceId))
				_registeredFactories.Add(interfaceId, instance);
		}

		public void UnregisterProgramFactory(ulong interfaceId)
		{
			if (interfaceId != 0)
				_registeredFactories.Remove(interfaceId);
		}

		public IProcess CreateUI(ulong interfaceId)
		{
			UiFactoryBase factoryBase;
			if (_registeredFactories.TryGetValue(interfaceId, out factoryBase))
				return factoryBase.CreateProgram();
			return null;
		}

		public List<IProcess> GetUiListByCategory(InterfaceCategory category)
		{
			IEnumerable<UiFactoryBase> factoryList;
			if (category != InterfaceCategory.All)
				factoryList = (from f in _registeredFactories where f.Value.UiCategory == category select f.Value);
			else
				factoryList = (from f in _registeredFactories select f.Value);

			return factoryList.Select(factory => factory.CreateProgram()).ToList();
		}
	}

	public abstract class UiFactoryBase
	{
		public abstract InterfaceCategory UiCategory { get; }
		public abstract IProcess CreateProgram();
	}
}